/**
 * created ho.viet.duan
 * 
 */
function _selectPage(selid, formId) {
	   sel = document.getElementById(selid);
	   if(sel != null) {
		   _goTo(sel.options[sel.selectedIndex].value, formId);
	   }  else {
		   return false;
	   }
}

function _goTo(index, formId) {
	try {
		document.getElementById("pagingInfo.indexPage").value = index;
		$("#"+formId).submit();
	} catch (e) {
		alert("_goTo(): " + e);
	}
}

// Set picture to image item
function setImage(imgId, uri) {
	var URL = NO_PICTURE_URL;
	if (uri != null && uri != '') {
		URL = ROOT_IMAGE_URL + uri;
	}
	$("#"+imgId).attr("src", URL);// Image
}
function getImage(uri) {
	var URL = NO_PICTURE_URL;
	if (uri != null && uri != '') {
		URL = ROOT_IMAGE_URL + uri;
	}
	return URL;// Image
}


$(document).ready(function() {
	
	// Upload Start
	$("#frmUploadResource_imgUpload").change(function(){
		$("#frmUploadResource_btnUpload").trigger('click');
		return false;
	});
	$("#frmUploadResource_btnUpload").click(function() {
		var options = {
			beforeSubmit : function(formData, jqForm, options) { // pre-submit
																	// callback
				var queryString = $.param(formData);
				if (queryString == '' || queryString == 'resourceFile=') {
					return false;
				}
				return true;
			},
			success : function(responseText, statusText) {
				_uploadSuccess(responseText, statusText);
			},
			error : function(xhr, ajaxOptions, thrownError) {
				alert(xhr.status);
				alert(thrownError);
			},
			url : UPLOAD_FILE_URL,
			type : 'post', // 'get' or 'post', override for form's 'method'
							// attribute
			dataType : 'json', // 'xml', 'script', or 'json' (expected server
								// response type)
			iframe : true
		};
		$('#frmUploadResource').ajaxSubmit(options);
		return false;
	});
	// Upload End
	
	$('input[placeholder], textarea[placeholder]').placeholder();

	/*+++ make active left menu **/
	var curUrl = window.location.href;
	var tabMap = {
			"notificationForm"	:	"notice",
			"friendRequests"	:	"notice", 
			"viewProfile"		:	"account",	 
			"accountStatus"		:	"account",
			"listFriend"		:	"account",
			"inviteFriendList"	:	"account",
			"listCustomer"		:	"account",
			"listBet"			:	"bet", 
			"listRecentBet"		:	"bet",
			"listRecommendBet"	:	"bet",	 
			"listTopBet"		:	"bet",	 
			"addBetForm"		:	"bet",	 
			"events"			:	"event" 	 	
	}

	if (curUrl) {
		var urlTemplate = "/{0}/{1}";
		var tabTemplate = "{0}-{1}-leftmenu";

		var url = "";
		var tab = "";
		$.each(tabMap, function(k, v, e) {
			url = urlTemplate.replace("{0}", v);
			url = url.replace("{1}", k);
			tab = tabTemplate.replace("{0}", v);
			tab = tab.replace("{1}", k);
			if (curUrl.indexOf(url) > -1) {
				$("#" + tab).addClass("forceSubitems open open selectedItem");
			}
		});
	}
	
});

function applyCloseUIButton() {
	//$('.closeuibutton').append('<div id="_btnClose" style="display: none;" class="closeuiicon" onclick="$(\'.closeuicontainer\').hide();" ></div>');
	$('.closeuicontainer').mouseenter(function(){
		$(this).find('[id=_btnClose]').show();
	}).mouseleave(function(){
		$(this).find('[id=_btnClose]').hide();
	});
}

function loadAccountStatus(customerId) {
	$.ajax({
		url : LOADACCOUNTSTATUS_URL,
		type: 'POST',
		data: {'customerInfo.customerId': customerId},
		dataType : 'json',
		iframe : true,
		success : function(data) {
			if(data.errorFlag == 0) {
				loadAccountStatusSuccess(data);
			}
		},
		error : function(xhr, ajaxOptions, thrownError) {
		}
	});
	setTimeout('loadAccountStatus("'+customerId+'")', 5000);
}

function loadAccountStatusSuccess(data) {
	$('#_txtAccountStatus_BetsJoinedCount').html(data.accountStatusModel.betsJoinedCount);
	$('#_txtAccountStatus_BetsCreatedCount').html(data.accountStatusModel.betsCreatedCount);
	$('#_txtAccountStatus_AvailableAmount').html('$' + data.accountStatusModel.availableAmount);
	$('#_txtAccountStatus_BettingAmount').html('$' + data.accountStatusModel.bettingAmount);
}

//Datetimepicker - starting vs ending for searching
function SetDateTimeForSearching(startId,endId){
	
	$.validator.addMethod("datetime", function(value, element) {
		return $.validator.methods['date'].call(this,$.datepicker.parseDate("dd/mm/yy",value),element);
		}  
	);
	
	$.validator.addClassRules({
		datetime : { datetime : true }
	});
	
	$('#' + startId).datetimepicker({
	    onClose: function(dateText, inst) {
	        var endDateTextBox = $('#' + endId);
	        if (endDateTextBox.val() != '') {
	            var testStartDate = new Date(dateText);
	            var testEndDate = new Date(endDateTextBox.val());
	            if (testStartDate > testEndDate)
	                endDateTextBox.val(dateText);
	        }
	        else {
	            //endDateTextBox.val(dateText);
	        }
	    },
	    onSelect: function (selectedDateTime){
	        var start = $(this).datetimepicker('getDate');
	        $('#ending_datetime').datetimepicker('option', 'minDate', new Date(start.getTime()));
	    }
	    ,dateFormat: "dd/mm/yy"
	});
	$('#' + endId).datetimepicker({
	    onClose: function(dateText, inst) {
	        var startDateTextBox = $('#' + startId);
	        if (startDateTextBox.val() != '') {
	            var testStartDate = new Date(startDateTextBox.val());
	            var testEndDate = new Date(dateText);
	            if (testStartDate > testEndDate)
	                startDateTextBox.val(dateText);
	        }
	        else {
	            //startDateTextBox.val(dateText);
	        }
	    },
	    onSelect: function (selectedDateTime){
	        var end = $(this).datetimepicker('getDate');
	        $('#' + startId).datetimepicker('option', 'maxDate', new Date(end.getTime()) );
	    }
	    ,dateFormat: "dd/mm/yy"
	});
}

function setDatePicker(dateId){
	$("#" + dateId).datepicker({
		buttonImageOnly : true,
		changeYear: true,
		yearRange: '1930:2020',
		dateFormat: "dd/mm/yy"
	});
}
function setDateTimePicker(dateId){
	$("#" + dateId).datetimepicker({
		buttonImageOnly : true,
		changeYear: true,
		yearRange: '1930:2020',
		dateFormat: "dd/mm/yy"
	});
}

function selectAll(chkChecks) {
	$('[id=' + chkChecks + ']').attr('checked', true);
}

function unSelectAll(chkChecks) {
	$('[id=' + chkChecks + ']').attr('checked', false);
}
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/, '');
};
String.prototype.toDate = function(format) {
	return string2Date(this, format);
};
Number.prototype.round = function(scale, roundType) {
	if(this == null) {
		return null;
	}
	if(scale == null) {
		return Math.round(this);
	}
	var s = 1;
	for(var i = 0; i < scale; i++) {
		s = s * 10;
	}
	if(roundType != null || roundType < 0) {
		return Math.round(this * s | 0) / s;	
	} else {
		return Math.round(this * s) / s;	
	}
};
function string2Date(value, format) {
	if (value == null || value == '') {
		return null;
	}
	if (value.indexOf(' ') == -1) {
		return null;
	}
	value = value.replace(/^\s+|\s+$/, '');
	var temp = value.split(' ');
	if (temp.length > 2) {
		return null;
	}
	var dateFormat = DATE_FORMAT_DATETIMEPICKER_DISPLAY;
	if (format != null && format != '') {
		dateFormat = format;
	}
	try {
		var date = $.datepicker.parseDate(DATE_FORMAT_DATETIMEPICKER_DISPLAY, temp[0]);
		var time = temp[1];
		return new Date($.datepicker.formatDate('mm/dd/yy', date) + ' ' + time);
	} catch (error) {
		return null;
	}
}

Date.prototype.formatDate = function(format) {
	var year = this.getFullYear() + '';
	var month = (this.getMonth() + 1) + '';
	if(this.getMonth() + 1 < 10) {
		month = '0' + month;
	}
	var date = this.getDate() + '';
	if(this.getDate() < 10) {
		date = '0' + date;
	}
	var date = new Date(year + "-" + month + "-" + date);
	var hour = this.getHours() + '';
	if(this.getHours() < 10) {
		hour = '0' + hour;
	}
	var minutes = this.getMinutes() + '';
	if(this.getMinutes() < 10) {
		minutes = '0' + minutes;
	}
	var seconds = this.getSeconds() + '';
	if(this.getSeconds() < 10) {
		seconds = '0' + seconds;
	}
	return $.datepicker.formatDate(format, date) + " " + hour + ":" + minutes + ":" + seconds;
};

function getPossibilityResult(r){
	if (r == 0) return POSSIBILITY_WRONG;
	if (r == 1) return POSSIBILITY_RIGHT;
	if (r == 2) return POSSIBILITY_NA;
	return;
}
var color = "white";
function __swap(obj){
	color = obj.style.backgroundColor;
	obj.style.backgroundColor = '#eeeeee';
}
function __reSwap(obj){
	obj.style.backgroundColor = color;
}
function scrollbar(){
	var scrollBorderColor	=	"#7F8E91";
	var scrollFaceColor		=	"#F0F6FF";
	with (document.body.style) {
		scrollbarDarkShadowColor	=	scrollBorderColor;
		scrollbar3dLightColor		=	scrollBorderColor;
		scrollbarArrowColor			=	"black";
		scrollbarBaseColor			=	scrollFaceColor;
		scrollbarFaceColor			=	scrollFaceColor;
		scrollbarHighlightColor		=	scrollFaceColor;
		scrollbarShadowColor		=	scrollFaceColor;
		scrollbarTrackColor			=	"white";
	}			
}